package org.imlinker.gui;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ResourceBundle;

import org.imlinker.login.Core;
import org.imlinker.util.Images;

@SuppressWarnings("serial")
public class TrayIconPopup extends PopupMenu {

	public TrayIconPopup(final Core core) {

		// 如果系统支持java托盘图标，则启动托盘图标
		if (SystemTray.isSupported()) {
			initialTrayIcon();
		}

		initComponents(core);
	}

	private void initComponents(final Core core) {
		ResourceBundle bundle = ResourceBundle
				.getBundle("org/imlinker/gui/Bundle"); // NOI18N

		// Show
		MenuItem item = new MenuItem(bundle.getString("TrayIconPopup.show"));
		item.addActionListener(new ActionListener() {

			public void actionPerformed(final ActionEvent e) {
				core.showMainWindow();
			}

		});
		add(item);

		// Exit.
		item = new MenuItem(bundle.getString("TrayIconPopup.exit"));
		item.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				Core.exit(0);
			}

		});
		add(item);

		trayIcon.addMouseListener(new MouseAdapter() {
			public void mouseClicked(final MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON1) {
					core.openFirstMessage();
				}
			}
		});
	}

	public void setMessageNum(final int number) {
		if (number == 0) {
			trayIcon.setImage(Images.getIcon0());
		} else if (number == 1) {
			trayIcon.setImage(Images.getIcon1());
		} else if (number == 2) {
			trayIcon.setImage(Images.getIcon2());
		} else if (number == 3) {
			trayIcon.setImage(Images.getIcon3());
		} else {
			trayIcon.setImage(Images.getIcon4());
		}
	}

	private void initialTrayIcon() {

		try {
			Image image = Images.getIcon0();
			trayIcon = new TrayIcon(image, "Linker", this);
			trayIcon.setImageAutoSize(true);

			SystemTray.getSystemTray().add(trayIcon);
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	private TrayIcon trayIcon;

}
